package ed25519

import (
	"encoding/base64"
	"fmt"
	"osiris/logger"

	"github.com/libp2p/go-libp2p/core/crypto"
)

// ED25519Sign 通过ocrypto.privKey给hash签名
//
//	@param privKey
//	@param hash 签名对象
//	@return string 签名(ECC+Base64)
//	@return error
func ED25519Sign(privKey crypto.PrivKey, hash string) (string, error) {
	signature, err := privKey.Sign([]byte(hash))
	if err != nil {
		logger.Error(map[string]interface{}{"[ocrypto] [Sign] " + hash: err})
	}
	signatureBase64 := base64.StdEncoding.EncodeToString(signature)

	return signatureBase64, err
}

// ED25519Verify 通过@param pubKey验证签名
//
//	@param pubKey
//	@param hash
//	@param signature
//	@return bool
func ED25519Verify(pubKey crypto.PubKey, hash string, signature []byte) bool {
	valid, err := pubKey.Verify([]byte(hash), signature)
	if err != nil {
		logger.Warn(map[string]interface{}{fmt.Sprintf("[ocrypto] [Verify]  hash: %s  signature: %s", hash, signature): err})
		return false
	}

	if !valid {
		logger.Warn(map[string]interface{}{fmt.Sprintf("[ocrypto] [Verify]  hash: %s  signature: %s", hash, signature): "fail"})
		return false
	}

	logger.Info(map[string]interface{}{fmt.Sprintf("[ocrypto] [Verify]  hash: %s  signature: %s", hash, signature): "succeed"})
	return true
}

func StrToED25519Sig(sigStr string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(sigStr)
}
